#include "StdAfx.h"
#include "speed_calculator.h"

speed_calculator::speed_calculator(void)
{
	this->sample_count_ = 6;
	this->file_size_ = 0;
	this->mode_ = e_use_this_time_trans_size;
}

speed_calculator::~speed_calculator(void)
{
}

void 
speed_calculator::set_sample(int trans_size)
{
	this->speed_list_.push_back(std::make_pair(trans_size, GetTickCount()));

	if ( this->speed_list_.size() > sample_count_ )
	{
		this->speed_list_.pop_front();
	}
}

int 
speed_calculator::get_speed()
{	
	int speed = 0;

	if ( e_use_this_time_trans_size == this->mode_  )
	{
		speed_list::iterator pos;
		std::pair<int, DWORD> elem = this->speed_list_.front();
		DWORD time1 = elem.second;
		elem = this->speed_list_.back();

		DWORD interval = elem.second - time1;

		if ( (interval == 0) || (this->sample_count_ > this->speed_list_.size() ) )
		{
			interval = interval + 500 * (this->sample_count_ - this->speed_list_.size());
		}

		int trans_size = 0;
		pos = this->speed_list_.begin();
		for ( ; pos != this->speed_list_.end(); ++pos )
		{
			trans_size += pos->first;
		}

		speed = trans_size * 1000 / interval; 

		if ( speed > this->file_size_ )
		{
			speed = this->file_size_;
		}
	}
	else if ( e_use_total_trans_size == this->mode_ )
	{
		speed_list::iterator pos;
		std::pair<int, DWORD> elem = this->speed_list_.front();
		DWORD time1 = elem.second;
		int trans_size1 = elem.first;

		elem = this->speed_list_.back();

		int trans_size = elem.first - trans_size1;
		DWORD interval = elem.second - time1;

		while ( interval < 1000 )
		{
			if ( interval == 0 )
			{
				interval = 1000;
			}
			else 
			{
				interval = interval * 2;
			}
		}

		speed = trans_size * 1000 / interval; 

 		/*TRACE(_T("get_speed: %d -> trans_size: %d, interval: %d, size: %d"), 
 			speed, trans_size, interval, this->speed_list_.size());*/

		if ( speed > this->file_size_ )
		{
			speed = this->file_size_;
		}
	}

	return speed;
}

void 
speed_calculator::set_file_size(int file_size)
{
	this->file_size_ = file_size;
	this->speed_list_.clear();
}

void
speed_calculator::set_sample_count(int sample_count)
{
	this->sample_count_ = sample_count;
}

/// basic check by fan05